<template>
  <div class="inner">
    <PageTitle title="包裹处理" />
    <!-- <el-button type="danger" class="wait-btn" @click="showHangUpList"
      >{{ hangUpCount }} 挂起</el-button
    > -->
    <div class="ibody">
      <div class="key">
        <div class="title">
          {{
            inputOrderfillNo ? inputOrderfillNo : "扫描包裹条码或输入包裹号查询"
          }}
        </div>
        <div class="dr-keyboard">
          <div
            :class="['dr-knum', activeKey === 7 ? 'active' : '']"
            @click="inputNum(7)"
          >
            <span>7</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 8 ? 'active' : '']"
            @click="inputNum(8)"
          >
            <span>8</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 9 ? 'active' : '']"
            @click="inputNum(9)"
          >
            <span>9</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 4 ? 'active' : '']"
            @click="inputNum(4)"
          >
            <span>4</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 5 ? 'active' : '']"
            @click="inputNum(5)"
          >
            <span>5</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 6 ? 'active' : '']"
            @click="inputNum(6)"
          >
            <span>6</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 1 ? 'active' : '']"
            @click="inputNum(1)"
          >
            <span>1</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 2 ? 'active' : '']"
            @click="inputNum(2)"
          >
            <span>2</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 3 ? 'active' : '']"
            @click="inputNum(3)"
          >
            <span>3</span>
          </div>
          <div
            :class="['dr-knum', activeKey === 0 ? 'active' : '']"
            @click="inputNum(0)"
          >
            <span>0</span>
          </div>
          <div
            :class="[
              'dr-knum',
              'dr-kn-delete',
              activeKey === 'delete' ? 'active' : ''
            ]"
            @click="deleteNum"
          >
            <span>删除</span>
          </div>
          <div
            :class="[
              'dr-knum',
              'dr-kn-submit',
              activeKey === 'submit' ? 'active' : ''
            ]"
            @click="inputSearchPackage"
          >
            <span>查询</span>
          </div>
        </div>
      </div>
      <div class="wait-list">
        <div class="title">已挂起包裹</div>
        <el-table
          :data="waitData"
          stripe
          style="width: 100%"
          row-class-name="table-normal-row"
          header-row-class-name="table-header-row"
        >
          <el-table-column prop="orderfillNo" label="包裹编号" />
          <el-table-column prop="shippingAddress" label="配送点" />
          <el-table-column prop="drugCount" label="药品数量" />
          <el-table-column prop="hangUpDate" label="挂起时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <div
                class="wh-btn"
                @click="showHangUpDetail(scope.row.orderfillNo)"
                type="primary"
              >
                查看
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog
      v-model="packageDetailVisible"
      title="包裹单详情"
      class="package-detail-dialog"
      width="800"
    >
      <div class="detail">
        <div class="d-row">
          <div class="d-col">单号</div>
          <div class="d-col">{{ packageDetail.orderfillNo }}</div>
          <div class="d-col">状态</div>
          <div class="d-col">
            {{
              packageDetail.status +
              (packageDetail.isHangUp === 1 ? "（已挂起）" : "")
            }}
          </div>
        </div>
        <div class="d-row">
          <div class="d-col">种类</div>
          <div class="d-col">{{ packageDetail.category }}</div>
          <div class="d-col">数量</div>
          <div class="d-col">{{ packageDetail.qantity }}</div>
        </div>
        <div class="d-row">
          <div class="d-col">拣货时间</div>
          <div class="d-col">{{ packageDetail.pickingTime }}</div>
          <div class="d-col">拣货员</div>
          <div class="d-col">{{ packageDetail.picker }}</div>
        </div>
        <div class="d-row">
          <div class="d-col">分拣时间</div>
          <div class="d-col">{{ packageDetail.sortingTime }}</div>
          <div class="d-col">分拣员</div>
          <div class="d-col">{{ packageDetail.sorter }}</div>
        </div>
        <div class="d-row">
          <div class="d-col">复核时间</div>
          <div class="d-col">{{ packageDetail.reviewingTime }}</div>
          <div class="d-col">复核人</div>
          <div class="d-col">{{ packageDetail.reviewer }}</div>
        </div>
        <div class="d-row">
          <div class="d-col">出库时间</div>
          <div class="d-col">{{ packageDetail.outWarehouseTime }}</div>
          <div class="d-col">出库员</div>
          <div class="d-col">{{ packageDetail.outWarehousePerson }}</div>
        </div>
      </div>
      <div class="drugs">
        <el-table
          :data="packageDetail.drugs"
          style="width: 100%"
          row-class-name="table-normal-row"
          header-row-class-name="table-header-row"
        >
          <el-table-column prop="drugId" label="产品编码" />
          <el-table-column label="药品" width="120">
            <template #default="scope">
              <div class="goods-detail-row">
                <el-image :src="scope.row.outerPackagePicUrl" fit="contain" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="通用名（商品名）" width="180">
            <template #default="scope">
              {{
                (scope.row.commonName || "") +
                (scope.row.productName ? `(${scope.row.productName})` : "")
              }}
            </template>
          </el-table-column>
          <el-table-column prop="standard" label="规格" />
          <el-table-column prop="amount" label="数量" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <div class="df-left">
            <div class="sum-btn" @click="printPackageOrder">
              <el-image :src="printPng" />
              <span class="sum-txt">打印包裹单</span>
            </div>
            <div class="sum-btn" @click="printOrder">
              <el-image :src="printPng" />
              <span class="sum-txt">打印面单</span>
            </div>
          </div>
          <div class="df-right">
            <div
              class="sum-btn"
              v-if="packageDetail.isHangUp === 1"
              @click="deleteHangUp"
            >
              <el-image :src="recoverPng" />
              <span>恢复分拣</span>
            </div>
            <div class="sum-btn stop" v-else @click="hangUp">
              <el-image :src="stopPng" />
              <span>暂缓分拣</span>
            </div>
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import PageTitle from "@/components/PageTitle.vue";
import { ref, onMounted, onUnmounted } from "vue";
import Drug from "@/components/Drug.vue";
import {
  getHangupPackagePendingNumApi,
  getPackageDetailApi
} from "@/api/package";
import {
  printPackgeApi,
  hangupPackageApi,
  deleteHangupPackageApi
} from "@/api/sorting";
import { getHangUpListApi, printHangUpSummaryApi } from "@/api/parcel";
import { printCheckOrderApi } from "@/api/check";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessageBox, ElMessage } from "element-plus";

import { debounce } from "@/utils/tools";
import printPng from "@/assets/img/print.png";
import stopPng from "@/assets/img/stop.png";
import recoverPng from "@/assets/img/recover.png";
const userStore = useUserStoreHook();
const warehouseId = userStore.userInfo.warehouseId;
const userId = userStore.userInfo.user;
const hangUpCount = ref(0);
let keyBoardTimeHandler = null;
const activeKey = ref();
const packageDetailVisible = ref(false);

const waitData = ref([
  {
    orderfillId: "1122",
    orderfillNo: "包裹单编码",
    hangUpDate: "2023-01-01 10:00:00"
  },
  {
    orderfillId: "1122",
    orderfillNo: "包裹单编码",
    hangUpDate: "2023-01-01 10:00:00"
  }
]);
const inputOrderfillNo = ref("");

// 包裹单详情
const packageDetail = ref({
  isHangUp: 0,
  orderfillId: "",
  orderfillNo: "",
  recipientName: "",
  category: "", //种类
  qantity: "", //数量
  status: "",
  pickingTime: "", //拣货时间
  picker: "",
  sortingTime: "", //分拣时间
  sorter: "",
  reviewingTime: "", //复核时间
  reviewer: "",
  outWarehouseTime: "", //出库时间
  outWarehousePerson: "",
  shippingAddress: "",
  drugs: []
});

function showHangUpDetail(orderfillNo) {
  searchPackage(orderfillNo);
}

async function showHangUpList() {
  waitData.value = await getHangUpListApi(warehouseId);
}

async function printDrugsSummary() {
  await printHangUpSummaryApi(waitData.value.map(item => item.orderfillId));
}

function hightKeyBoard(value) {
  clearTimeout(keyBoardTimeHandler);
  activeKey.value = value;
  keyBoardTimeHandler = setTimeout(() => {
    activeKey.value = "";
  }, 100);
}
function inputNum(value) {
  inputOrderfillNo.value = String(inputOrderfillNo.value) + String(value);
  hightKeyBoard(value);
}
function deleteNum() {
  hightKeyBoard("delete");
  if (inputOrderfillNo.value.length > 0) {
    inputOrderfillNo.value = inputOrderfillNo.value.slice(0, -1);
  }
}

function inputSearchPackage() {
  searchPackage(inputOrderfillNo.value);
}
const searchPackage = debounce(
  async function searchPackage(orderfillNo) {
    // console.log("searchPackage");
    orderfillNo = orderfillNo || inputOrderfillNo.value;
    // console.log("orderfillNo:", orderfillNo);
    packageDetail.value = await getPackageDetailApi(orderfillNo);
    packageDetailVisible.value = true;
  },
  1000,
  true
);

async function printOrder() {
  // 打印面单
  await printCheckOrderApi([packageDetail.value.orderfillId]);
  ElMessage({
    type: "success",
    message: "打印成功"
  });
}
async function printPackageOrder() {
  // 打印包裹单
  await printPackgeApi([packageDetail.value.orderfillId]);
  ElMessage({
    type: "success",
    message: "打印成功"
  });
}

function init() {
  packageDetailVisible.value = false;
  getHangUpCount();
}

async function deleteHangUp() {
  await deleteHangupPackageApi(packageDetail.value.orderfillId, userId);
  ElMessage({
    type: "success",
    message: "已解除挂起"
  });

  init();
}
async function hangUp() {
  try {
    await hangupPackageApi(packageDetail.value.orderfillId, userId);
  } catch (error) {
    console.log("error:", error);
  }
  ElMessage({
    type: "success",
    message: "挂起成功"
  });
  init();
}

async function getHangUpCount() {
  const res = await getHangupPackagePendingNumApi(warehouseId);
  hangUpCount.value = res && res.count;
}

let scanInputNumber = "";
let keyLastTime = 0;

function enterEvent(orderfillNo) {
  console.log("enterEvent orderfillNo:", orderfillNo);
  // 扫码包裹单
  searchPackage(orderfillNo);
}
function keyDownEvent(event) {
  let gap = 0;
  if (keyLastTime) {
    gap = new Date().getTime() - keyLastTime;
    // 大于50毫秒，则判定为人输入
    if (gap > 50) {
      gap = 0;
      scanInputNumber = "";
    }
  }
  keyLastTime = new Date().getTime();
  if (gap < 50) {
    const theEvent = event || window.event;
    // console.log("theEvent:", theEvent);
    const code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code !== 13 && theEvent.key.length === 1) {
      scanInputNumber += theEvent.key;
    }

    if (code === 13) {
      scanInputNumber = scanInputNumber.replace(/\D*/, "");
      enterEvent(scanInputNumber);
      scanInputNumber = "";
      keyLastTime = 0;
    }
  }
}

onMounted(() => {
  getHangUpCount();
  showHangUpList();
  document.addEventListener("keydown", keyDownEvent);
});
onUnmounted(() => {
  document.removeEventListener("keydown", keyDownEvent);
});
</script>
<style lang="scss" scoped>
.inner {
  position: relative;
}

.wait-btn {
  position: absolute;
  top: 20px;
  right: 20px;
}
.ibody {
  width: 100%;
  margin-top: 30px;
  .key {
    margin-top: 20px;
    padding: 20px;
    box-sizing: border-box;
    background-color: white;
    border-radius: 10px;
    .title {
      height: 32px;
      line-height: 32px;
      text-align: center;
      font-size: 22px;
      font-weight: bold;
      color: #b5b5c3;
    }
    .dr-keyboard {
      display: grid;
      grid-template-rows: repeat(4, 50px);
      grid-template-columns: repeat(3, 100px);
      grid-gap: 10px;
      width: 320px;
      margin: auto;
      margin-top: 20px;
      .dr-knum {
        height: 50px;
        text-align: center;

        // border: 1px dashed #bbb;
        background: #f5f8fa;

        /* 表单/单元格描边 */
        box-shadow: 0px 1px 0px 0px #e6e6e6;
        border-radius: 4px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        user-select: none;
        &.active {
          // border-top: 4px solid #bbb;
          // box-shadow: inset 0px 2px 2px 0px #d8d8d8;
          // border-top-style: solid;
          // border-top-color: #d8d8d8;
          box-shadow: inset 0px 1px 5px 0px rgba(0, 0, 0, 0.3);
          // span {
          //   margin-top: -2px;
          // }
          // box-shadow: inset 0px 2px 2px 1px #bbb;
        }
      }
      .dr-kn-delete {
        color: white;
        /* 表单/单元格描边 */
        box-shadow: 0px 1px 0px 0px #e6e6e6;
        background: #ff7f65;
        border: none;
        border-radius: 4px;
      }
      .dr-kn-submit {
        border: none;
        color: white;

        background: #3689f5;
        /* 表单/单元格描边 */
        box-shadow: 0px 1px 0px 0px #e6e6e6;
        border-radius: 4px;
      }
    }
  }
  .wait-list {
    padding: 20px;
    border-radius: 10px;
    background-color: white;
    margin-top: 30px;
    .title {
      font-size: 22px;
      font-weight: bold;
      color: #3f4254;
    }
    .el-table {
      margin-top: 20px;
      .wh-btn {
        border-style: solid;
      }
    }
  }
}
.package-detail-dialog {
  .detail {
    margin: auto;
    width: 100%;
    text-align: center;
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    .d-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #eee;
      height: 40px;
      line-height: 40px;
      .d-col {
        border-right: 1px solid #eee;
        &:nth-child(odd) {
          width: 15%;
        }
        &:nth-child(even) {
          width: 35%;
        }
      }
    }
  }
  .drugs {
    padding: 0px 30px;
    margin-top: 30px;
    :deep(.goods-detail-row) {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 100px;
      background-color: #d8d8d8;
      .el-image {
        width: 80px;
        height: 80px;
        flex-shrink: 0;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .df-left,
  .df-right {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .sum-btn {
      width: 200px;
      height: 50px;
      opacity: 1;
      border: 1px solid #50cd89;
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 0em;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      cursor: pointer;
      color: #50cd89;
      .el-image {
        width: 34px;
        height: 34px;
        object-fit: contain;
        margin-right: 5px;
      }

      &.stop {
        border: 1px solid #ff7f65;
        color: #ff7f65;
      }
    }
  }
}
</style>
